package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.properties.ShopProperties;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.BaiduMapUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {


    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ShopProperties shopProperties;
    @Autowired
    private BaiduMapUtil baiduMapUtil;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //1.地址合法性判断（收货地址为空、超出配送范围、购物车为空）不合法抛出异常
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //2.查询当前用户购物车数据是否存在
        Long currentId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(currentId);

        /*
            检查用户的收货距离商家门店是否超出配送范围
         */
        //商家地址
        String shopAddress = shopProperties.getAddress();
        //商家经纬度
        try {
            String adminAddress = baiduMapUtil.getLngAndLatByAddressName(shopAddress);
            String userAddress = baiduMapUtil.getLngAndLatByAddressName(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
            Long distance = baiduMapUtil.getadderss(adminAddress, userAddress);
            if (distance>5000) {
                throw new AddressBookBusinessException("距离过远");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


        //获得购物车数据
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null && shoppingCartList.size() == 0) {
            //判断购物车是否有数据 ,如果没有数据 抛出异常
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //3.构造订单数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, order);
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setUserId(currentId);
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setPayStatus(Orders.UN_PAID);
        order.setOrderTime(LocalDateTime.now());

        //向订单插入一条数据
        orderMapper.insert(order);

        //4.订单明细数据

        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            //将购物车每个订单明细复制到 新建 订单明细
            BeanUtils.copyProperties(cart, orderDetail);
            //放入订单id
            orderDetail.setOrderId(order.getId());
            //将 购物车明细加入 订单集合
            orderDetailList.add(orderDetail);
        }

        //向明细表 插入n条数据
        orderDetailMapper.insertBatch(orderDetailList);

        //5.清理当前用户的购物车中的数据
        shoppingCartMapper.deleteByUserId(currentId);

        //6.封装返回数据
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(order.getId())
                .orderAmount(order.getAmount())
                .orderNumber(order.getNumber())
                .orderTime(order.getOrderTime())
                .build();

        return orderSubmitVO;

    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();


        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo,userId);


        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
        //////////////////////////////////////////////
        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + outTradeNo);

        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
//        orderMapper.update(orders);
    }

    /**
     * 历史订单查询
     * 思路:
     * 1. 分页查询插件 输入 页码 页数
     * 2.创建分页查询DTO对象,在三层之间传递 放入当前用户id,和状态 ,将分页查询传到mapper层查询 订单数据并封装为list集合
     * 3.创建订单VO对象  判断查询结果, 循环每一个订单对象
     * 4.得到每一个订单id 根据订单id查询订单明细 并封装 为集合 创建 单一订单VO对象 将订单属性复制
     * 并将订单明细集合放入订单VO集合中 并将当前对象放入集合中
     * 5.返回查询总数 和 集合
     *
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult pageQuery(int page, int pageSize, Integer status) {
        //设置分页
        PageHelper.startPage(page, pageSize);
        //获取用户id
        Long userId = BaseContext.getCurrentId();
        // 查找 放入 id 和状态
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setStatus(status);
        ordersPageQueryDTO.setUserId(userId);
        //分页查询 从数据库 并封装 page 订单类
        Page<Orders> pageResult = orderMapper.pageQuery(ordersPageQueryDTO);
        //创建 订单VO对象
        List<OrderVO> orderVOList = new ArrayList<>();
        //判断 并循环拿出 分页查询 订单
        if (pageResult != null && pageResult.size() > 0) {
            for (Orders orders : pageResult) {
                //获取订单id
                Long ordersId = orders.getId();
                //根据订单id获取订单明细并封装为 订单明细集合
                List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(ordersId);
                OrderVO orderVO = new OrderVO();
                //将每一个订单 复制到 订单VO对象返回前端
                BeanUtils.copyProperties(orders, orderVO);
                //用订单VO中的set方法将订单明细集合放入 对象中
                orderVO.setOrderDetailList(orderDetailList);
                //将订单VO放入订单集合中返回前端
                orderVOList.add(orderVO);
            }
        }


        return new PageResult(pageResult.getTotal(), orderVOList);
    }

    /**
     * 查询订单详情
     * 思路:
     * 1.根据前端传入id在数据库中得到订单
     * 2.根据订单id在订单明细中查询 并封装 为集合
     * 3.创建订单VO对象 将订单属性复制到VO对象 并将 订单明细集合放入 VO对象
     * 4.返回VO对象给前端
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO detail(Long id) {
        //根据id查询订单
        Orders orders = orderMapper.getById(id);
        //根据订单id查询订单明细
        List<OrderDetail> list = orderDetailMapper.getByOrderId(orders.getId());
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(list);
        return orderVO;
    }

    /**
     * 取消订单
     * 思路:
     * 1.根据id查询订单 并判断订单是否存在 不存在抛出订单不存在异常
     * 2. 判断订单状态  1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 大于2  抛出订单状态异常
     * 3. 创建新的订单对象 获得 当前订单 id 取消原因 取消时间 状态 更新 订单
     *
     * @param id
     */
    @Override
    public void cancelById(Long id) {
        //根据id查询订单
        Orders orders = orderMapper.getById(id);

        //判断订单是否存在
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //判断订单状态
        if (orders.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //创建新订单放入数据库
        Orders order = new Orders();
        order.setStatus(Orders.CANCELLED);
        order.setCancelTime(LocalDateTime.now());
        order.setId(orders.getId());
        order.setCancelReason("用户取消");

        orderMapper.update(order);

    }

    /**
     * 再来一单
     * 思路:
     * 1.获取用户id 查询订单详情 封装集合
     * 2.创建购物车集合 判断并遍历 订单明细  创建购物车对象 将订单明细属性复制到购物车对象中,
     * 放入当前用户id和创建时间 将当前购物车对象加入到购物车集合中去
     * 3.将 当前购物车对象插入到购物车表中
     *
     * @param id
     */
    @Override
    public void repetition(Long id) {
        //根据订单id查询订单明细封装
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        Long userId = BaseContext.getCurrentId();
        //再来一单 将订单明细放入购物车并插入购物车表 当用户点击下单 调用 下单方法
        List<ShoppingCart> shoppingCartList = new ArrayList<>();
        //判断得到的订单明细不为空且有数据
        if (orderDetailList != null && orderDetailList.size() > 0) {
            for (OrderDetail orderDetail : orderDetailList) {
                //创建单个购物车对象 将获得的订单明细属性复制到购物车对象中
                ShoppingCart shoppingCart = new ShoppingCart();
                BeanUtils.copyProperties(orderDetail, shoppingCart);
                shoppingCart.setUserId(userId);
                shoppingCart.setCreateTime(LocalDateTime.now());
                shoppingCartList.add(shoppingCart);
            }

        }
        shoppingCartMapper.insertBatch(shoppingCartList);

    }

    /**
     * 订单搜索
     *思路:
     * 1.调用分页查询插件 输入 页数和每页查询条数  用前端传入查询条件从数据库查询 ,结果为List<Orders> 强转为 Page<Orders>
     * 2. 创建订单VO对象集合 将查询结果封装 为订单集合 判断不为空且有数据开始循环遍历订单集合拿出单个订单
     * 3.创建 单个订单VO对象  将每个订单复制到VO对象中  用订单获得订单id在订单明细中查询数据并封装 订单明细集合
     * 4.循环将订单明细转为字符串并放入 集合中
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult search(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        //根据查询
        Page<Orders> page = (Page<Orders>) orderMapper.search(ordersPageQueryDTO);

        List<OrderVO> orderVOList = new ArrayList<>();
        List<Orders> ordersList = page.getResult();
        //判断集合 是否为空 且有数据
        if (ordersList != null && ordersList.size() > 0) {
            for (Orders orders : ordersList) {

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);

                //查询订单菜品详细
                List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

                //因为订单VO对象所需订单菜品信息是String类型 所以将每条订单拼接为字符串
                List<String> orderDishList = new ArrayList<>();
                for (OrderDetail orderDetail : orderDetailList) {
                    //将订单明细中的名字和数量用字符串拼接 加入到String集合中
                    String orderDish = orderDetail.getName() + "✖" + orderDetail.getNumber() + ";";
                    orderDishList.add(orderDish);
                }
                //拼接订单明细 放到订单VO对象中 并加入到订单VO集合
                String orderDishes = String.join("", orderDishList);

                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }


        return new PageResult(page.getTotal(), orderVOList);
    }

    /**
     * 各个状态的订单数量统计
     *
     * @return
     */
    @Override
    public OrderStatisticsVO count() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();

        Integer toBeConfirmed = orderMapper.status(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.status(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.status(Orders.DELIVERY_IN_PROGRESS);

        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);

        return orderStatisticsVO;
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO reference(Long id) {
        //获得当前订单id
        Orders orders = orderMapper.getById(id);
        //查询当前订单详细 封装集合
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);

        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        //当前订单id

        Orders orders = new Orders();
        orders.setId(ordersConfirmDTO.getId());
        //放入订单状态 不是 前端传入状态
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.confirm(orders);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void reject(OrdersRejectionDTO ordersRejectionDTO) {
        //从 订单表查找订单
        Orders orders = orderMapper.getById(ordersRejectionDTO.getId());
        //判断订单状态
        if (orders != null || orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            Orders order = new Orders();
            order.setStatus(Orders.CANCELLED);
            order.setId(orders.getId());
            order.setCancelReason(ordersRejectionDTO.getRejectionReason());
            order.setCancelTime(orders.getCancelTime());
            orderMapper.update(order);

        }
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Long id = ordersCancelDTO.getId();
        //从订单表查询订单
        Orders orders = orderMapper.getById(id);
        //判断订单状态
        if (orders==null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //如果处于接单状态 进行取消订单
        if (orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //支付状态改为 退款
            orders.setStatus(Orders.REFUND);
        }

        //更新订单
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());

        orderMapper.update(orders);
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        //根据id查询订单
        Orders orders = orderMapper.getById(id);
        //检验订单是否存在 并且状态为已接单
        if (orders.getId() != null && orders.getStatus()!=Orders.CONFIRMED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //更新订单状态 并改为 派送
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);

    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        //用订单id从数据库查询订单
        Orders orders = orderMapper.getById(id);
        //判断订单是否为空 且状态是否在派送中
        if (orders != null || orders.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orders.setStatus(Orders.COMPLETED);
        orderMapper.update(orders);

    }

    /**
     * 用户催单
     *
     * @param id
     */
    public void reminder(Long id) {
        // 查询订单是否存在
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //基于WebSocket实现催单
        Map map = new HashMap();
        map.put("type", 2);//2代表用户催单
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

}








































































































